import { ChatRoomModel } from '@/database/models/chatRoom.model';
import { ChatHistoryModel } from '@/database/models/chatHistory.model';

import type {
  CreateChatRoomParams,
  ChatRoomAddUserParams,
  CreateNewChatRecordParams
} from './types/chat.types';

import type { ChatRoomDetail } from '@/typings/chat';

export class ChatService {
  // 创建一个聊天室
  static createNewChatRoom = async (params: CreateChatRoomParams) => {
    const room = new ChatRoomModel({
      creator: params.creatorId,
      users: params.users
    });
    const result = await room.save();
    return result.toObject<ChatRoomDetail>();
  }

  // 聊天室添加用户
  static addUsersTochatRoom = async (params: ChatRoomAddUserParams) => {
    const result = await ChatRoomModel.findByIdAndUpdate(params.roomId, {
      $push: {
        users: {
          $each: params.users
        }
      }
    });
    return result.toObject<ChatRoomDetail>();
  }

  // 创建一条聊天记录
  static createNewChatRecord = async (params: CreateNewChatRecordParams) => {
    const chat = new ChatHistoryModel({
      creator: params.creatorId,
      roomId: params.roomId,
      type: params.type,
      message: params.message
    });
    const result = await chat.save();
    return result.toObject();
  }
}